package com.alperez.androidsmscamera;

import org.json.JSONException;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.EditText;
import android.widget.Toast;

import com.alperez.androidsmscamera.model.SuperRootAccount;
import com.alperez.androidsmscamera.model.UserAccount;
import com.alperez.androidsmscamera.model.UserAccount.AccountType;

public class EditAccountActivity extends Activity {
	private enum EditMode {
		EDIT_ACCOUNT_FLEX_TYPE, EDIT_ACCOUNT_FIXED_TYPE, NEW_ACCOUNT_FLEX_TYPE, NEW_ACCOUNT_FIXED_TYPE
	}
	
	
	private EditMode mActivityEditMode = EditMode.NEW_ACCOUNT_FLEX_TYPE; // Initialize by default in case of no extras of extras are empty
	private UserAccount mInitialAccountToEdit;
	private AccountType mFixedAccTypeArgument;
	
	private UserAccount mCurrentEditingAccount;
	
	private AlertDialog mSuperRootAccessDialog;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		if (savedInstanceState == null) {
			//--- Initial launch ---
			Bundle extras = getIntent().getExtras();
			if (extras != null) {
				String strAcc = extras.getString("account_to_edit"); // NULL is returned if no arg
				if (strAcc != null) {
					mInitialAccountToEdit = new SuperRootAccount(this);
					try {
						mInitialAccountToEdit.fromJson(strAcc);
					} catch (JSONException e) {
						// Probably we received non super root account. Try parse plain UserAccount
						try {
							mInitialAccountToEdit = new UserAccount(0, AccountType.ANONYMOUS_USER);
							mInitialAccountToEdit.fromJson(strAcc);
						} catch(JSONException e1) {
							// Now it's really an error
							finishWithToast("Bad arg error. User account can not be recreated from JSON - " + e.getMessage());
							return;
						}
					}
				}
				
				if (extras.containsKey("fixed_account_type")) {
					try {
						mFixedAccTypeArgument = UserAccount.accountTypeFromString(extras.getString("fixed_account_type"));
					} catch(IllegalArgumentException e) {
						finishWithToast("Bad arg error. " + e.getMessage());
						return;
					}
				}
				
				boolean flBlockAccType = extras.getBoolean("block_account_type", false);
				
				//--- Define edit mode for activity ---
				if (mInitialAccountToEdit != null) {
					mActivityEditMode = (flBlockAccType) ? EditMode.EDIT_ACCOUNT_FIXED_TYPE : EditMode.EDIT_ACCOUNT_FLEX_TYPE;
					mCurrentEditingAccount = (mInitialAccountToEdit instanceof SuperRootAccount) ? new SuperRootAccount(this, (SuperRootAccount)mInitialAccountToEdit) : new UserAccount(mInitialAccountToEdit);
				} else if (flBlockAccType && mFixedAccTypeArgument != null) {
					mActivityEditMode = EditMode.NEW_ACCOUNT_FIXED_TYPE;
				} else {
					mActivityEditMode = EditMode.NEW_ACCOUNT_FLEX_TYPE;
				}
				
				if (mCurrentEditingAccount == null) { // Define initial default value for editing
					mCurrentEditingAccount = new UserAccount(0, AccountType.DEFINED_USER);
				}
			}
		} else {
			//--- Activity has been recreated ---
			String strEditMode = savedInstanceState.getString("activity_edit_mode");
			if (strEditMode.equals("EDIT_ACCOUNT_FLEX_TYPE")) {
				mActivityEditMode = EditMode.EDIT_ACCOUNT_FLEX_TYPE;
			} else if (strEditMode.equals("EDIT_ACCOUNT_FIXED_TYPE")) {
				mActivityEditMode = EditMode.EDIT_ACCOUNT_FIXED_TYPE;
			} else if (strEditMode.equals("NEW_ACCOUNT_FLEX_TYPE")) {
				mActivityEditMode = EditMode.NEW_ACCOUNT_FLEX_TYPE;
			} else if (strEditMode.equals("NEW_ACCOUNT_FIXED_TYPE")) {
				mActivityEditMode = EditMode.NEW_ACCOUNT_FIXED_TYPE;
			} else {
				throw new IllegalStateException("WTF?!");
			}
			if (savedInstanceState.containsKey("fixed_account_type")) {
				mFixedAccTypeArgument = UserAccount.accountTypeFromString(savedInstanceState.getString("fixed_account_type"));
			}
			if (savedInstanceState.containsKey("account_to_edit")) {
				mInitialAccountToEdit = new UserAccount(1, AccountType.ANONYMOUS_USER);
				try {
					mInitialAccountToEdit.fromJson(savedInstanceState.getString("account_to_edit"));
				} catch (JSONException e) { throw new IllegalStateException(e); }
			}
			mCurrentEditingAccount = new UserAccount(0, AccountType.ANONYMOUS_USER);
			try {
				mCurrentEditingAccount.fromJson(savedInstanceState.getString("curr_editing_account"));
			} catch (JSONException e) { throw new IllegalStateException(e); }
		}
		
		
		//--- Find UI elements ---
		
		
		//--- Populate or show Access dialog for Super root user ---
		if (((savedInstanceState == null) && (mCurrentEditingAccount instanceof SuperRootAccount)) || ((savedInstanceState != null) && savedInstanceState.getBoolean("ask_super_root_access"))) {
			showSuperRootAccessDialog();
		} else {
			populateUiWiCurrentlyEditingAccount();
		}
		
	}
	
	
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		switch(mActivityEditMode) {
		case EDIT_ACCOUNT_FIXED_TYPE:
			outState.putString("activity_edit_mode", "EDIT_ACCOUNT_FIXED_TYPE");
			break;
		case EDIT_ACCOUNT_FLEX_TYPE:
			outState.putString("activity_edit_mode", "EDIT_ACCOUNT_FLEX_TYPE");
			break;
		case NEW_ACCOUNT_FIXED_TYPE:
			outState.putString("activity_edit_mode", "NEW_ACCOUNT_FIXED_TYPE");
			break;
		case NEW_ACCOUNT_FLEX_TYPE:
			outState.putString("activity_edit_mode", "NEW_ACCOUNT_FLEX_TYPE");
			break;
		default:
			throw new IllegalStateException("WTH?!");
		}
		if (mFixedAccTypeArgument != null) {
			outState.putString("fixed_account_type", UserAccount.accountTypeAsString(mFixedAccTypeArgument));
		}
		if (mInitialAccountToEdit != null) {
			try {
				outState.putString("account_to_edit", mInitialAccountToEdit.toJson());
			} catch (JSONException e) { throw new IllegalStateException(e); }
		}
		try {
			outState.putString("curr_editing_account", mCurrentEditingAccount.toJson());
		} catch (JSONException e) { throw new IllegalStateException(e); }
		
		outState.putBoolean("ask_super_root_access", (mSuperRootAccessDialog != null));
	}
	
	
	private void populateUiWiCurrentlyEditingAccount() {
		//TODO Do main work here
	}
	
	
	
	private void showSuperRootAccessDialog() {
		if (mSuperRootAccessDialog != null) {
			mSuperRootAccessDialog.dismiss(); mSuperRootAccessDialog = null;
		}
		mSuperRootAccessDialog = new AlertDialog.Builder(this).setTitle(R.string.edit_account_super_root_access_dialog_title).setPositiveButton(android.R.string.ok, new OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				if (mSuperRootAccessDialog != null) {
					String passw = ((EditText) mSuperRootAccessDialog.findViewById(R.id.edit1)).getText().toString();
					if (!TextUtils.isEmpty(passw) && passw.equals(mInitialAccountToEdit.getPassword())) {
						populateUiWiCurrentlyEditingAccount();
						return;
					}
				}
				EditAccountActivity.this.setActivityResultNoAccess();
				EditAccountActivity.this.finish();
			}
		}).setNegativeButton(android.R.string.no, new OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				EditAccountActivity.this.setActivityResultNoAccess();
				EditAccountActivity.this.finish();
			}
		}).setOnCancelListener(new OnCancelListener() {
			
			@Override
			public void onCancel(DialogInterface dialog) {
				EditAccountActivity.this.setActivityResultNoAccess();
				EditAccountActivity.this.finish();
			}
		}).create();
		mSuperRootAccessDialog.setView(getLayoutInflater().inflate(R.layout.super_root_edit_access_dialog_content, null));
		mSuperRootAccessDialog.show();
	}
	
	
	
	
	
	
	private void setActivityResultNoAccess() {
		Intent intent = new Intent();
		intent.putExtra("error_message", getString(R.string.edit_account_error_access_denied));
		setResult(RESULT_CANCELED, intent);
	}
	
	private void finishWithToast(String message) {
		Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
		finish();
	}
	
}
